package com.apes.framework.plugin.fsm.util;

import com.apes.framework.util.CronExpression;
import com.apes.framework.util.DateUtil;
import lombok.Data;
import lombok.SneakyThrows;

import java.util.Date;

@Data
public class TaskParam {
    /**
     * 间隔
     **/
    private int delay;
    /**
     * 重复次数
     **/
    private int repeat;
    /**
     * 单位
     **/
    private int timeUnit;

    /**
     * 算法
     **/
    private String algorithm;

    private Date next;

    public TaskParam() {
    }

    public TaskParam(int delay, int repeat, int timeUnit, String algorithm) {
        this.delay = delay;
        this.repeat = repeat;
        this.timeUnit = timeUnit;
        this.algorithm = algorithm;
    }

    @SneakyThrows
    public void calc(Date baseTime) {
        if ("increase".equals(algorithm)) {
            next = DateUtil.add(baseTime, timeUnit, delay);
        } else if ("time-point".equals(algorithm)) {
            String cronExpression = String.format("0 0 %s * * ?", delay);
            next = new CronExpression(cronExpression).getNextValidTimeAfter(baseTime);
        } else {
            throw new RuntimeException("时间计算方式不允许为空！");
        }
    }

    @Override
    public String toString() {
        return "TaskParam{" +
                "delay=" + delay +
                ", repeat=" + repeat +
                ", timeUnit=" + timeUnit +
                ", algorithm='" + algorithm + '\'' +
                ", next=" + next +
                '}';
    }
}
